"""人员相关接口"""
from datetime import datetime
import random
import pytz
from flask import Blueprint, request, g
import dao.person as person_dao
from util.validation import validate_fields
from util.response import response
from dao import project_person_relation

person_api = Blueprint('person_api', __name__)


@person_api.route("/api/project/<int:project_id>/person", methods=['GET'])
def index(project_id):
    """人员列表"""
    status = request.args.get('status', None, type=int)
    if status is not None and status not in [1, 2, 3, 4]:
        return response(422, "status 参数无效 [1, 2, 3, 4]", {})
    result = person_dao.index(project_id, status)
    return response(0, "success", result)


@person_api.route("/api/project/<int:project_id>/person", methods=["POST"])
def store(project_id):
    """添加人员"""
    data = request.get_json()
    _, msg = validate_fields(data, ["name", "id_card"])

    if msg:
        return response(422, msg, {})

    # 检查人员是否存在
    person = person_dao.exists(data['id_card'])

    if person:
        person_id = person_dao.find_by_id_card(data['id_card'])

        # 修改人员信息
        person_dao.update(data, person_id)

        # 关联项目和人员
        if not project_person_relation.exists(project_id, person_id):

            new_person_id = project_person_relation.create(data, project_id, person_id)
        else:
            new_person_id = project_person_relation.update(data, project_id, person_id)
    else:
        # 添加人员信息
        person_id = person_dao.create(data)
        # 关联项目和人员
        new_person_id = project_person_relation.create(data, project_id, person_id)

    return response(0, "success", {"new_person_id": new_person_id})


@person_api.route("/api/project/<int:project_id>/person/<int:person_id>", methods=["DELETE"])
def person_destroy(project_id, person_id):
    """删除人员"""
    if not project_person_relation.exists(project_id, person_id):
        return response(422, "该人员不存在", {})

    with g.db_conn.cursor() as cursor:
        project_person_relation_id = project_person_relation.destroy(cursor, project_id, person_id)
        g.db_conn.commit()
    return response(0, "success", {"project_person_relation_id": project_person_relation_id})


@person_api.route("/api/project/undone_person", methods=["GET"])
def user_list():
    """ 待签到 ｜ 已签到"""
    result = person_dao.undone()
    return response(0, "success", result)
    

@person_api.route("/api/user-info", methods=['GET'])
def user_info():
    """用户信息"""
    params = {key: request.args.get(key) for key in ['verify_code', 'id_card', 'status'] if request.args.get(key)}
    if not params:
        return response(422, "条件参数不能为空", {})

    result = project_person_relation.info(**params)
    return response(0, "success", result)


@person_api.route("/api/project/<int:project_id>/update_status", methods=['POST'])
def project_update(project_id):
    """确认发送"""
    with g.db_conn.cursor() as cursor:
        project_person_relation.update_status(cursor, project_id)
        g.db_conn.commit()
    return response(0, "success", {})


@person_api.route("/api/user/status", methods=['PUT'])
def status_update():
    """修改状态"""
    data = request.get_json()
    # 检查字段是否存在且不为空
    _, error_message = validate_fields(data, ['id', 'status'])
    if error_message:
        return response(422, error_message, {})

    if data["status"] not in [2, 3]:
        return response(422, "status 参数 必须为 2 或 3", {})

    set_data = []

    current_timestamp = int(datetime.now(pytz.timezone('Asia/Shanghai')).timestamp())
    set_data.append("updated_at = " + str(current_timestamp))

    # 签到记录 签到时间
    if data["status"] == 2:
        set_data.append("signin_at = " + str(current_timestamp))

    if data.get('role_id') == 3 and data.get('status') == 2:
        set_data.append("identity = " + str(random.randint(1000, 9999)))

    # 签到记录 签退时间
    if data["status"] == 3:
        set_data.append("signout_at = " + str(current_timestamp))

    set_data.append("status = " + str(data['status']))

    set_data_str = ",".join(set_data)
    with g.db_conn.cursor() as cursor:
        sql_query = f"""UPDATE project_person_relation SET {set_data_str} WHERE id = %s RETURNING person_id;"""
        cursor.execute(sql_query, (data['id'],))
        g.db_conn.commit()

    if data.get('role_id') == 3 and data.get('status') == 2:
        return response(0, "success", person_dao.find_by_id(data.get('id')))
    return response(0, "success", {})


@person_api.route("/api/user_cabinet", methods=['GET'])
def user_cabinet():
    """柜子匹配人员"""
    page_number = request.args.get('page_number', 1, type=int)
    page_size = request.args.get('page_size', 10, type=int)
    keyword = request.args.get('keyword', None, type=str)
    _ = request.args.get('reset', None, type=int)
    sort_by =  request.args.get('sort_by', 'grid_no', type=str)
    sort_order = request.args.get('sort_order', 'asc', type=str)
    result = person_dao.user_cabinet(page_number, page_size, keyword, sort_by, sort_order)
    total_rows = person_dao.total(keyword)
    return response(0, "success", {"data": result, **person_dao.page_info(page_number, page_size, total_rows)})


@person_api.route("/api/authenticate", methods=['POST'])
def authenticate():
    """认证"""
    data = request.get_json()
    _, msg = validate_fields(data, ["account", "password"])
    if msg:
        return response(422, msg, {})
    
    data, msg = person_dao.identity(account=data.get('account'), password=data.get('password'))
    
    if msg:
        return response(422, msg, {})
    
    return response(0, "success", data)
